
/** 
 * @author Ervinne Sodusta
 * 
 *  This script must be import first before any socket related scripts.
 * online_user.js handles logging in and out to the socket server. This script
 * will also handle the UI changes for each user that goes online or offline.
 */

(function() {

    var SORT_DESCENDING = '0';
    var SORT_ASCENDING = '1';

    var socket;
    var currentUserData;

    var eventPublishAddress;

    var viewType = '2014-design';

    $(document).on('socketActivated', function(event) {

        socket = event.socket;
        currentUserData = event.currentUserData;

        //  all events from this script will be published to this publish address/addresses
        eventPublishAddress = ['general_functions_' + currentUserData.companyId];

        //  check which view is currently being used
        if ($('#online-users-container').length > 0) {
            viewType = $('#online-users-container').attr('view-type');
        }

        socketLogin();

        initializeEvents();

//        //  initialize events only if the page contains an online users list
//        if ($('.onlineUsers').html()) {
//            initializeEvents();
//        }
    });

    function socketLogin() {

        var registrationData = {
            publishAddresses: eventPublishAddress,
            userData: currentUserData
        };

        socket.emit('register', registrationData);
    }

    function initializeEvents() {

        socket.on('userLoggedIn', function(user) {

            var onlineUserCount = parseInt($('.countUOnline').html().trim());

            if (onlineUserCount == 0) {
                //  remove the "No Users Online" display first before adding users.
                $('.onlineUsers').html('');
            }

            //  only add the user display if it's not existing,
            //  display may duplicate when the user goes idle then active again
            if ($('#online_user_' + user.id).length == 0) {
                //  build the online user display            

                var html = '<a id="online_user_' + user.id + '" data-id="' + user.id + '" href="' + user.profileLink + '" class="online-user">';

                if (viewType == '2014-design') {
                    html += user.image;
                } else {
                    html += '<img class="avatar onlineUser userAvatar" data-original-title="' + user.displayName + '" src="' + $(user.image).attr('src') + '" width=23 height=23>';
                }

                html += '</a>';

                $('.onlineUsers').append(html);
            }

            //  display the online user in the online users chat box
            if ($('.fl-chat-online-users').length > 0) {

                //  only add the user display if it's not existing,
                //  display may duplicate when the user goes idle then active again                
                if ($('.fl-chat-online-user[data-id="' + user.id + '"]').length == 0) {
                    //  create the ui from the template
                    var onlineUserTemplate = $('#fl-chat-ui-templates').find('.fl-chat-online-user');
                    var onlineUserListItemTemplate = onlineUserTemplate.closest('li');

                    var onlineUserListItem = onlineUserListItemTemplate.clone(true);
                    var onlineUser = onlineUserListItem.find('a');

                    onlineUser.attr('data-id', user.id);
                    onlineUser.attr('data-display-name', user.displayName);

                    onlineUser.find('img').attr('src', $(user.image).attr('src'));
                    onlineUser.find('.fl-online-chat-name').html(user.displayName);

                    $('.fl-chat-online-users-content ul').append(onlineUserListItem);
                }
            }

            onlineUserCount++;
            $('.countUOnline').html(onlineUserCount);

            //  remove duplicates
            var seen = {};
            $('.online-user').each(function() {
                var dataId = $(this).attr('data-id');
                if (seen[dataId]) {
                    $(this).remove();
                } else {
                    seen[dataId] = true;
                }
            });

            //  display the users in ascending order
            $('.onlineUsers').html(sortElements($('.onlineUsers').find('a'), 'data-id'), SORT_ASCENDING);

            //  reassign the tooltip for each users
            $(".online-user > .userAvatar").tooltip('destroy');
            $(".online-user > .userAvatar").tooltip();
        });

        socket.on('userLoggedOut', function(user) {

            //  online users in the dashboard
            $('.onlineUsers').find('a[data-id="' + user.id + '"]').remove();

            //  online users in the chatbox
            $('.fl-chat-online-users-content').find('a[data-id="' + user.id + '"]').remove();

            if ($('.countUOnline').length() > 0) {
                var onlineUserCount = parseInt($('.countUOnline').html().trim());

                if (onlineUserCount > 0) {
                    onlineUserCount--;
                    $('.countUOnline').html(onlineUserCount);
                }

                if (onlineUserCount == 0) {
                    $('.onlineUsers').html('<b>No Users Online.</b>');
                }
            }

        });

    }

    function sortElements(elements, sortByAttribute, sortType) {

        var html = '';
        var temp;

        var attributeI, attributeJ;

        for (var i = 0; i < elements.length; i++) {
            for (var j = 0; j < elements.length; j++) {

                if (i == j) {
                    continue;
                }

                attributeI = $(elements[i]).attr(sortByAttribute);
                attributeJ = $(elements[j]).attr(sortByAttribute);

                //  allow proper sorting of either integers or strings
                if (!isNaN(attributeI) && !isNaN(attributeJ)) {
                    attributeI = parseInt(attributeI);
                    attributeJ = parseInt(attributeJ);
                }

                if (!sortType || sortType == SORT_ASCENDING) {
                    if (attributeI < attributeJ) {
                        temp = elements[i];
                        elements[i] = elements[j];
                        elements[j] = temp;
                    }
                } else if (sortType == SORT_DESCENDING) {
                    if (attributeI > attributeJ) {
                        temp = elements[i];
                        elements[i] = elements[j];
                        elements[j] = temp;
                    }
                }
            }
        }

        for (var i = 0; i < elements.length; i++) {
            html += parseElementToString(elements[i]);
        }
        return html;

    }

    function parseElementToString(element) {
        if (!element) {
            return '';
        }

        var container = document.createElement('div');
        var html;

        $(container).append(element);
        html = $(container).html();

        return html;
    }
})();